<?php
/**
 * 抢购活动管理
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
class RushBuyController extends Controller
{
    protected $model;
    protected $return;
   
    public function __construct(){
        header("Access-Control-Allow-Origin: *");
        $this->model = D('RushBuy');
        $this->return = array('errcode'=>0, 'errmsg'=>'ok');
        if(ACTION_NAME != 'login'){
            $admin = session('rush_admin');
            if (!$admin) {
                $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录'));
            }
        }
    }

    public function login()
    {
        $username = I('post.username', '', 'trim');
        $password = I('post.password', '', 'trim');
        $map['username'] = $username;
        $map['is_deleted'] = 0;
        $admin = M("RushBuyAdmin")->where($map)->find();
        if (!$admin) {
            $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'账号密码错误'));
        }
        $pass = strtolower(md5($password.$admin['salt']));
        if($pass != $admin['password']){
            $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'账号密码错误'));
        }else{
            session('rush_admin', $admin['username']);
            M("RushBuyAdmin")->where($map)->save(array('last_login_time'=>time()));
            $this->ajaxReturn($this->return);
        }
    }

    public function view()
    {
        $id = I('post.id', 0, 'intval');
        $list = $this->model->getCouponList($id);
        if ($list !== false) {
                $list = array_merge($list, $this->return);
            }else{
                $list = $this->model->getErrMsg();
            }
        $this->ajaxReturn($list, 'JSON');
    }

    public function record()
    {

        $data['name'] = I('post.keyword', '', 'trim');
        $data['start'] = I('post.start', '', 'trim');
        $data['end']   = I('post.end', '', 'trim');
        $data['pageIndex'] = I('post.page', 1, 'intval');
        $res = $this->model->getRecord($data);
        if ($res !== false) {
                $res = array_merge($res, $this->return);
            }else{
                $res = $this->model->getErrMsg();
            }
        $this->ajaxReturn($res, 'JSON');
    }

     //导出
    public function recordDownload()
    {
        $data['start'] = I('post.start', '', 'trim');
        $data['end']   = I('post.end', '', 'trim');
        $data['name'] = I('post.keyword', '', 'trim');
        
        $data['page'] = I('post.page', 1, 'intval');
        $data['page_size'] = I('page_size', 20, 'intval');

        $res = $this->model->getRecord($data, true);
        $sheetindex=array(
            'A'=>array('index'=>'A1','name'=>'序号','size'=>'20'),
            'B'=>array('index'=>'B1','name'=>'活动名称','size'=>'20'),
            'C'=>array('index'=>'C1','name'=>'抢品名称','size'=>'20'),
            'D'=>array('index'=>'D1','name'=>'用户名称','size'=>'20'),
            'E'=>array('index'=>'E1','name'=>'手机号码','size'=>'20'),
            'F'=>array('index'=>'F1','name'=>'卡号','size'=>'20'),
            'G'=>array('index'=>'G1','name'=>'优惠码','size'=>'20'),
            'H'=>array('index'=>'H1','name'=>'参与时间','size'=>'20'),
        );
        $title = '中奖名单';
        $type = 19;
        phpExcel($sheetindex,$res['data'],$title,$type);
        exit;
    }

    //列表
    public function index()
    {
        $data['title']   = I('post.title', '', 'trim');//名称
        $data['keyword'] = I('post.keyword', '', 'trim');
        $data['id']     = I('post.id', 0, 'intval');//ID
     //   $data['status'] = I('post.status', -1, 'intval');//状态0下线1上线
        $data['start']  = I('post.start', '', 'trim');//开始区间
        $data['end']    = I('post.end', '', 'trim'); //结束区间。
     //   $data['type']   = I('post.type', 0, 'intval'); //类型1业主2师傅
     //   $data['admin_user'] = I('post.admin_user', '', 'trim'); //创建人
        $pageIndex = I('post.page', 1, 'intval');

        $res = $this->model->getList($data, $pageIndex);
        if ($res !== false) {
            $res = array_merge($res, $this->return);
        }else{
            $res = $this->model->getErrMsg();
        }
        $this->ajaxReturn($res, 'JSON');
       
    }
    //新增
    public function add()
    {
        $data['title'] = I('post.title', '', 'trim');
        $data['sub_title'] = I('post.sub_title', '', 'trim');
        $data['price'] = I('post.price', 0, 'intval');
        $data['start_time'] = I('post.start_time', '', 'trim');
        $data['end_time'] = I('post.end_time', '', 'trim');
        $data['logo'] = I('post.logo', '', 'trim');
        $data['link'] = I('post.link', '', 'trim');
        $data['prize_name'] = I('post.prize_name', '', 'trim');
        $data['description'] = I('post.description', '', 'trim');
        $data['description'] = htmlspecialchars($data['description']);
        $res = $this->model->addRush($data);
        if ($res) {
            $this->ajaxReturn($this->return, 'JSON');
        }else{
            $this->ajaxReturn($this->model->getErrMsg());
        }
        
    }
    //编辑
    public function edit()
    {
        if (IS_POST) {
            $id = I('post.id', 0, 'intval');
            $map['id'] = $id;
            $map['is_deleted'] = 0;
            $rush = $this->model->where($map)->find();
            if (!$rush) {
                $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'找不到对应的数据'),'JSON');    
            }else{
                $rush['start_time'] = date('Y-m-d H:i:s', $rush['start_time']);
                $rush['end_time'] = date('Y-m-d H:i:s', $rush['end_time']);
                $rush['description'] = htmlspecialchars_decode($rush['description']);
                $this->return['data'] = $rush;
                $this->ajaxReturn($this->return,'JSON');
            }  
        }else{
            $this->display();
        }
    }

    public function del()
    {
        $id = I('post.id', 0, 'intval');
        $map['id'] = $id;
        $res = $this->model->where($map)->save(array('is_deleted'=>1));
        if ($res !== false) {
            $this->ajaxReturn($this->return,'JSON');
        }else{
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'删除失败'));
        }
    }
    //更新数据
    public function update()
    {
        $data['title'] = I('post.title', '', 'trim');
        $data['sub_title'] = I('post.sub_title', '', 'trim');
        $data['price'] = I('post.price', 0, 'intval');
        $data['start_time'] = I('post.start_time', '', 'trim');
        $data['end_time'] = I('post.end_time', '', 'trim');
        $data['logo'] = I('post.logo', '', 'trim');
        $data['prize_name'] = I('post.prize_name', '', 'trim');
        $data['id'] = I('post.id', 0, 'intval');
        $data['link'] = I('post.link', '', 'trim');
        $data['description'] = I('post.description', '', 'trim');
        $data['description'] = htmlspecialchars($data['description']);
      //  Log::write(var_export($data,true),'data');
        $res = $this->model->updateRush($data);
        if ($res) {
            $this->ajaxReturn($this->return, 'JSON');
        }else{
            $this->ajaxReturn($this->model->getErrMsg());
        }
        
    }


    
   public function import()
   {
        $id = I('post.id', 0, 'intval');
        $map['id'] = $id;
        $map['is_deleted'] = 0;
        $act = M('RushBuy')->where($map)->find();
        if (!$act) {
            $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'活动不存在'));
        }
        require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel.class.php');
        if(!empty($_FILES)){
            $config = array(
                'exts'=>array('xlsx', 'xls'),
                'maxSixe' => 1024 * 1024 * 5,
                'rootPath' =>'./Uploads/',
                'savePath' =>'image/',
                'subName'  =>array('date', 'Ymd'),
                'driver' =>'Local'
                );
            $upload = new \Think\Upload($config);
            if(!$info = $upload->upload()){
                $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>$upload->getError()));
            }
            $filename = $upload->rootPath.$info['file']['savepath'].$info['file']['savename'];
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if($extension == 'xlsx'){
                require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel/Reader/Excel2007.php');
                $reader = new \PHPExcel_Reader_Excel2007();   
                $obj = $reader->load($filename, $encode = 'utf-8');
            }elseif ($extension == 'xls'){
                require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel/Reader/Excel5.php');
                $reader = new \PHPExcel_Reader_Excel5();
                $obj = $reader->load($filename, $encode = 'utf-8');
            }
            $sheet = $obj->getSheet(0);
            $row = $sheet->getHighestRow();
            $col = $sheet->getHighestColumn();
            $isExist = 0;
            $insert = 0;
            for($i = 1; $i<= $row; $i++){
                $coupon = $obj->getActiveSheet()->getCell("A".$i)->getValue(); 
                if($coupon instanceof \PHPExcel_RichText){
                    $coupon = $coupon->getPlainText();
                }
                if(!is_string($coupon)){
                    break;
                }
                $data['coupon'] = trim($coupon);
                if (!$data['coupon']) {
                    break;
                }
                $data['rush_id'] = $id;
                $data['is_deleted'] = 0;

                $res = M('RushBuyCoupon')->where($data)->find();
                if($res){
                    $isExist++;
                }else{
                    $insert++;
                    $data['add_time'] = time();
                    M('RushBuyCoupon')->add($data);
                }
            }
            unlink($filename);
            $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'操作成功，本次新增数'.$insert.',已存在数'.$isExist));
        }else{
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
        }

    }
    
    public function adminList()
    {
        $res = $this->model->getAdminList();
        if ($res !== false) {
                $res = array_merge($res, $this->return);
            }else{
                $res = $this->model->getErrMsg();
            }
        $this->ajaxReturn($res, 'JSON');
    }
    
    public function addAdmin()
    {
        $data['username'] = I('post.username', '', 'trim');
        $data['password'] = I('post.password', '', 'trim');
        $data['confirm_password'] = I('post.confirm_password', '', 'trim');
        $data['remark'] = I('post.remark', '', 'trim');

        $res = $this->model->addAdmin($data);
        if ($res) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn($this->model->getErrMsg());
        }

    }

    public function saveAdmin()
    {
        $data['new_password'] = I('post.new_password', '', 'trim');
        $data['password'] = I('post.password', '', 'trim');
        $data['confirm_password'] = I('post.confirm_password', '', 'trim');
        $data['id'] = I('post.id', 0, 'intval');

        $res = $this->model->saveAdmin($data);
        if ($res) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn($this->model->getErrMsg());
        }

    }
    public function delAdmin()
    {
        $id = I('post.id', 0, 'intval');
        $res = $this->model->delAdmin($id);
        if ($res) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn($this->model->getErrMsg());
        }
    }

    //重置用户密码
    public function resetAdmin()
    {
        $admin = session('rush_admin');
        if ($admin != 'admin') {
            $this->ajaxReturn(array('errcode'=>20001, 'errmsg'=>'权限不够'));
        }

        $id = I('post.id', 0, 'intval');
        $model = M("RushBuyAdmin");
        $map['id'] = $id;
        $map['is_deleted'] = 0;
        $info = $model->where($map)->find();
        if(!$info){
            $this->ajaxReturn(array('errcode'=>20002, 'errmsg'=>'用户'));
        }
        $salt = rand(1, 1000000);
        $pass = strtolower(md5('123456'.$salt));
        $res = $model->where($map)->save(array('password'=>$pass, 'salt'=>$salt));
        if ($res !== false) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'重置失败'));
        }
    }

    public function upload()
    {

        if(!empty($_FILES)){
            $upload = new \Think\Upload(C('UPLOAD_CONFIG'));
            $info = $upload->upload($_FILES);
            $urls = array();
            if (!$info) {// 上传错误提示错误信息
                $data=array('err_code'=>403,'state'=>$upload->getError());
                echo json_encode($data);
                //$this->ajaxReturn($data,'JSON');
            } else {// 上传成功 获取上传文件信息
                foreach ($info as $file) {
                    //$url = $file['savepath'] . $file['savename'];
                   // var_dump($info);exit;
                    array_push($urls, $file);
                }
                $data=array('err_code'=>200,'err_msg'=>$urls,'state'=>'SUCCESS','url'=>$urls[0]['url']);
                Log::write(var_export($data, true), 'info');
                echo json_encode($data);
            //    $this->ajaxReturn($data);
            }
        }else{
            echo json_encode(array('state'=>'没有文件被上传'));
        }
    }

}
